import React, { ReactNode } from "react";
import ReactDOM from "react-dom";
import User from "./User";
import { getBlockUsers, removeBlockUser, USER_LIST_KEY } from "./utils";

interface IState { blockedList: Array<User> }
export default class Popup extends React.Component<any, IState> {
  constructor(props: any) {
    super(props);
    this.state = {
      blockedList: [],
    };
  }

  async componentDidMount() {
    let blockedList = await getBlockUsers();
    console.log(blockedList);
    this.setState({
      blockedList: blockedList
    });

    // chrome.browserAction.setBadgeText({ text: `${blockedList.length}` })

    // 监听屏蔽列表的改变
    chrome.storage.onChanged.addListener(async (changes, namespace) => {
      for (let [key, { oldValue, newValue }] of Object.entries(changes)) {
        if (key == USER_LIST_KEY) {
          let blockedList = await getBlockUsers();
          this.setState({
            blockedList: blockedList
          });
          // chrome.browserAction.setBadgeText({ text: `${blockedList.length}` })
        }
      }
    });
  }

  // 处理按钮点击事件
  async handleClick(user: User) {
    await removeBlockUser(user.id);
  }

  // 渲染按钮
  public render(): ReactNode {
    const listItems = this.state.blockedList.map((user) => {
      let userName = user.name;
      if (userName && userName.length > 20) {
        userName = `${userName.slice(0, 20)}...`;
      }
      return <li key={user.name} style={{
        color: "gray",
        whiteSpace: "nowrap"
      }}>
        <button
          onClick={async () => { await this.handleClick(user); }}
          style={{
            display: "inline-block",
            color: "#fff",
            background: "#0d6efd",
            borderRadius: ".25rem",
            border: "1px solid transparent",
            borderColor: "#0d6efd"
          }}>移除</button>
        <span style={{
          maxWidth: "50px",
          whiteSpace: "nowrap",
          textOverflow: "ellipsis",
          overflow: "hidden",
          marginLeft: "6px"
        }}>{userName}</span>
      </li>
    }
    );
    return (
      <div style={{
        padding: "6px 16px 6px 16px"
      }}>
        <div style={{
          fontWeight: "bold",
          whiteSpace: "nowrap",
        }}>屏蔽列表</div>
        <ul style={{
          listStyle: "none",
          padding: 0
        }}>
          {this.state.blockedList.length == 0 ? <p style={{ whiteSpace: "nowrap" }}>当前屏蔽列表为空</p> : listItems}
        </ul>
      </div>
    )
  }
}

ReactDOM.render(
  <React.StrictMode>
    <Popup />
  </React.StrictMode>,
  document.getElementById("root")
);
